package com.qianyu.project.web.controller.base;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.qianyu.project.entity.AttachemenInfo;
import com.qianyu.project.service.IAttachemenInfoService;
import com.qianyu.project.utils.Result;
import com.qianyu.project.utils.ResultTool;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
public class UploadController {

    @Autowired
    private IAttachemenInfoService attachemenInfoService;

    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    private static final String accessKeyId = "LTAI4GCXS6Qi9BqpB7S55n3u";

    private static final String accessKeySecret = "PfFpcEmXMvzUUChJAViMo9DcNcQkag";

    private static final String bucketName = "qy-file-bucket";

    @RequestMapping("/upload")
    public Result upload(MultipartFile multipartfile, String folder) throws IllegalStateException, IOException {
        //拿到文件的后缀名
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //拿到文件的后缀名
        String suffix = StringUtils.getFilenameExtension(multipartfile.getOriginalFilename());
        //指定一个随机的文件名
        String fileName = UUID.randomUUID().toString();
        //拼接路径
        String savePath = folder + "/" + fileName + "." + suffix;

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, savePath, multipartfile.getInputStream());

        ossClient.putObject(putObjectRequest);
        //获取文件url
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, savePath, expiration);

        ossClient.shutdown();
        //返回在服务器的位置
        return ResultTool.success(null, url.toString());
    }

    @RequestMapping("/uploads")
    public Result upload(@RequestParam("file") MultipartFile[] multipartfiles, String folder) throws IllegalStateException, IOException {
        //拿到文件的后缀名
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        if (multipartfiles == null || multipartfiles.length == 0) {
            return ResultTool.failure("未上传任何文件");
        }

        List<AttachemenInfo> attachemenInfos = Lists.newArrayList();

        for (MultipartFile multipartFile : multipartfiles) {
            //拿到文件的后缀名
            String suffix = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
            //指定一个随机的文件名
            String fileName = UUID.randomUUID().toString();
            //拼接路径
            String savePath = folder + "/" + fileName + "." + suffix;

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, savePath, multipartFile.getInputStream());

            ossClient.putObject(putObjectRequest);
            //获取文件url
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            // 生成URL
            URL url = ossClient.generatePresignedUrl(bucketName, savePath, expiration);

            AttachemenInfo attachemenInfo = new AttachemenInfo();
            attachemenInfo.setFileName(multipartFile.getOriginalFilename());
            attachemenInfo.setFilePath(url.toString());
            attachemenInfo.setFileType(suffix);
            attachemenInfo.setUploadDate(DateUtil.today());
            attachemenInfos.add(attachemenInfo);
        }

        attachemenInfoService.saveBatch(attachemenInfos);

        ossClient.shutdown();

        List<Integer> ids = Lists.newArrayList();
        attachemenInfos.iterator().forEachRemaining(attachemenInfo -> ids.add(attachemenInfo.getId()));

        return ResultTool.success(CollectionUtil.join(ids, ",")).put("files",attachemenInfos);
    }
}
